package bll

import (
	"context"

	"manager/event"
	"manager/model"
	"manager/model/entity"
	"manager/store"
	"manager/store/postgres"
	"time"
)

type voiceNode struct {
	iVoiceNode store.IVoiceNode
}

var VoiceNode = &voiceNode{
	iVoiceNode: postgres.VoiceNode,
}

func (a *voiceNode) init() func() {
	return func() {}
}

func (a *voiceNode) onEvent(*event.Data) {}

// Create 创建
func (a *voiceNode) Create(ctx context.Context, in *model.VoiceNodeCreateRequest) error {
	var (
		err error
	)

	// 构建创建现场数据
	c := buildVoiceNode(in)
	_, err = a.iVoiceNode.Create(ctx, c)
	return err
}

// Update 更新
func (a *voiceNode) Update(ctx context.Context, in *model.VoiceNodeUpdateRequest) error {
	var (
		dict = make(map[string]interface{})
	)

	updateAt := time.Now().Unix()
	in.UpdatedAt = &updateAt

	if in.Name != nil {
		dict["name"] = in.Name
	}

	if in.SeriesType != nil {
		dict["series_type"] = in.SeriesType
	}

	if in.VoiceId != nil {
		dict["voice_id"] = in.VoiceId
	}

	if in.UpdatedAt != nil {
		dict["updated_at"] = in.UpdatedAt
	}

	// do other update here

	return a.iVoiceNode.Update(ctx, in.Id, dict)
}

// Delete 删除
func (a *voiceNode) Delete(ctx context.Context, in *model.VoiceNodeDeleteRequest) error {
	return a.iVoiceNode.Delete(ctx, in.Id)
}

// List 列表查询
func (a *voiceNode) List(ctx context.Context, in *model.VoiceNodeListRequest) (*model.VoiceNodeListResponse, error) {
	var (
		err   error
		total int
		list  []*entity.VoiceNode
		out   = &model.VoiceNodeListResponse{}
	)

	if total, list, err = a.iVoiceNode.List(ctx, in); err != nil {
		return nil, err
	}

	out.Total = total
	out.List = model.VoiceNodesEntityToDto(list)

	return out, nil
}

// Find 列表查询
func (a *voiceNode) Find(ctx context.Context, in *model.VoiceNodeInfoRequest) (*model.VoiceNodeInfo, error) {
	var (
		err  error
		data *entity.VoiceNode
		out  = &model.VoiceNodeInfo{}
	)

	if data, err = a.iVoiceNode.Find(ctx, in); err != nil {
		return nil, err
	}

	out = model.VoiceNodeEntityToDto(data)
	return out, nil
}

// buildVoiceNode 构建创建数据现场
func buildVoiceNode(in *model.VoiceNodeCreateRequest) *entity.VoiceNode {
	// todo: check the entity is required
	return &entity.VoiceNode{

		Name: in.Name,

		SeriesType: in.SeriesType,

		VoiceId: in.VoiceId,

		CreatedAt: time.Now().Unix(),

		UpdatedAt: time.Now().Unix(),
	}
}
